#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# copyright (c) 2010 by The Codedrawer Team
#
# 成员
# xkhhdx(HD.Huo)	viking9345(C.Cai)	renxing225(X.Ren)
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# 代码来自：http://code.google.com/p/codedrawer/
#
#--- 更新记录 ---
#成员		时间			简述
#xkhhdx		20:30 2010-8-29	添加了对行号的支持
#xkhhdx		23:50 2010-8-21	修正了某些情况不会进行特殊字符转换的BUG
#xkhhdx		16:17 2010-6-25	简单的修改了测试代码将 python 标记以了出来 修改了注释信息
#xkhhdx		1:45 2010-6-20	基本的框架已经完工
#
#--- 计划列表 ---
#提出者		时间			是否解决	解决者	计划简述		解决简述
#xkhhdx		1:53 2010-6-20	否			n/a		完善转义处理	n/a
#xkhhdx		1:47 2010-6-20	否			n/a		添加异常处理	n/a
#

import re
import logging
from style_html import *

class style_blank():
    def prepare( self ):
        self.parent.marker_dict["comment"] = r"<\g<0>>"
        self.parent.marker_dict["quoted_string"] = r"{\g<0>}"
        self.parent.marker_dict["keyword"] = r"[\g<0>]"

    def prerender_escape_sequence(self, text):
        """  """

        return text

    def postrender_escape_sequence(self, text):
        """  """

        return text

    def rearrange(self,text, showlinenumber = True):
        """  """

        if not showlinenumber:
            return text

        lines = text.split("\n"); text = ""

        magnitude = len("%d" % ( len(lines) ) )

        for i in range(0, len(lines)):
        	text = text + "\n" + self.make_line_number(i+1, magnitude) + lines[i]
        return text

    def make_line_number( self, num ):

        return '[%4d]' % num

class code_render():
    """ 对代码进行标记 """
    showlinenumber = 0
    def __init__(self, render_style="blank"):
        """ 构造函数 """
        self.regex_dict = {	"comment"		:	"",
                           	"quoted_string"	:	"",
                           	"keyword"		:	""}

        self.marker_dict = {	"comment"		:	"",
                            	"quoted_string"	:	"",
                            	"keyword"		:	""}

        self.verifier_dict = {	"spliter"		:	None,
                              	"comment"		:	None,
                              	"quoted_string"	:	None,
                              	"keyword"		:	None}

        self.code_buffer = ""
        self.rendered_code_buffer = ""

        try:
            self.style = eval( "style_" + render_style + "()" )
        except Exception:
            print Exception
            self.style=style_blank()

        self.prerender_escape_sequence_func = self.style.prerender_escape_sequence
        self.postrender_escape_sequence_func =  self.style.postrender_escape_sequence

        self.prepare()

        self.style.parent = self
        self.style.prepare()

    def prepare(self):
        """ 准备正则式、正则库等信息 这个由子类实现"""
        print u"prepare() 这个函数应该在子类中进行重载"

    def linenumber(self, show = True):
        self.showlinenumber = show

    def render(self):
        """ 进行转换 """
        # 分割代码
        self.rendered_code_buffer = ""

        splited_code = self.verifier_dict["spliter"].split(self.code_buffer)
        code_len = len(splited_code)

        for i in range(0, code_len):
            if splited_code[i]!=None and splited_code[i]!="":

                # 先进行特殊字符转换
                splited_code[i] = self.prerender_escape_sequence_func (splited_code[i])

                if self.verifier_dict["comment"].match(splited_code[i]) != None:    # 如果是注释
                    splited_code[i] = re.sub(self.verifier_dict["comment"], self.marker_dict["comment"], splited_code[i])

                elif self.verifier_dict["quoted_string"].match(splited_code[i]) != None:    # 如果是字串
                    splited_code[i] = re.sub(self.verifier_dict["quoted_string"], self.marker_dict["quoted_string"], splited_code[i])

                elif self.verifier_dict["keyword"].search(splited_code[i])!=None:    # 如果是关键字
                    if self.verifier_dict["keyword"].search(splited_code[i]).group()!="": #and self.verifier_dict["keyword"].search(splited_code[i]).group()[0]!="\"":
                        splited_code[i] = re.sub(self.regex_dict["keyword"], self.marker_dict["keyword"], splited_code[i])
                else:
                    pass

        for i in range(0, code_len):
            if splited_code[i] != None:
                self.rendered_code_buffer = self.rendered_code_buffer + splited_code[i]

        self.rendered_code_buffer = self.style.rearrange(self.rendered_code_buffer, self.showlinenumber)

if __name__ == "__main__":
    print u"如果要测试这个模块 请使用 ./test.py"

